const log = require('./log/logFunction.js').logs;
const config = require('./config.js');
const Koa = require('koa');
const Router = require('koa-router');
const views = require('koa-views');
const static = require('koa-static');
const resBody = require('koa-bodyparser');
const pageRouter = require('./router/page.js');
const datasRouter = require('./router/dataReport.js');
const DB = require('./mongoDBConfig/index.js');
const app = new Koa();
const https = require('https');
const fs = require('fs')

const checkToken = require('./dataReport/login.js').checkToken;
// 返回数据格式封装
const resSend = function() {
    let resCode, 
        resMsg, 
        resData;
    return async (ctx, next) => {
        ctx.resSend = {
            setCode(code) {
                resCode = code;
                resMsg = 'success';
                resData = undefined;
            },
            setMsg(msg) {
                resMsg = msg;
            },
            setData(data) {
                resData = data;
            },
            send() {
                ctx.body = {
                    code: resCode,
                    msg: resMsg,
                    data: resData
                }
            }
        }
        await next();
    }
}

app
    .use(resBody())
    .use(resSend())
    .use(async (ctx, next) => {
        // 请求进入与发出日志打印
        const reqType = ctx.method;
        log.debug(`收到请求 ${ctx.url}  ${reqType}`);
        if (reqType === 'POST') {
            log.debug('接收到的数据');
            console.log(ctx.request.body);
            log.debug('=====================');
        }
        await next();
        log.debug(`返回请求 ${ctx.url}  ${reqType} ${ctx.response.status}`);
        if (reqType === 'POST') {
            log.debug('返回的数据为');
            console.log(ctx.body);
            log.debug('=====================');
        }
    })
    .use(checkToken)    
    /*.use(async (ctx, next) => {
        // 跨域响应头添加
        await next();
        ctx.response.header['Access-Control-Allow-Origin'] = '*';
        ctx.response.header['Access-Control-Allow-Methods'] = 'GET,POST';
        ctx.response.header['Access-Control-Allow-Headers'] = 'x-requested-with,content-type,token';
    })*/
    .use(views(config.webPath, {
        extension: config.webType
    }))
    .use(static(config.staticPath));

// 路由
let router = new Router()
router.use('/', pageRouter.routes(), pageRouter.allowedMethods());
router.use('/dataReport', datasRouter.routes(), datasRouter.allowedMethods());


app
    .use(router.routes())
    .use(router.allowedMethods());
app.listen(config.port, () => {
    log.info('server is start port => ', config.port)
})
// https.createServer(config.sslOption, app.callback()).listen(config.port, () => {
//     log.info('server is start port => ', config.port)
// });
app.on('error', (err, ctx) => {
  log.error('server error', err, ctx);
  logger.error('服务器出现错误');
  logger.error(err, ctx);
});